/**
 * 
 */
package org.compiere.process;

import java.math.BigDecimal;
import java.sql.Timestamp;

import org.adempiere.exceptions.AdempiereException;
import org.compiere.model.MFI_C_PaymentLine;
import org.compiere.model.Mhrmpayment;
import org.compiere.model.Mhrmpaymentlist;
import org.compiere.model.X_C_Payment;
import org.compiere.model.X_FI_C_PaymentLine;
import org.compiere.util.Env;
import org.compiere.util.Msg;

/**
 * @author A.Yerzhanov
 * Apr 18, 2013
 */
public class fiPayment extends SvrProcess {
	
	private X_C_Payment payment = null;
	private X_FI_C_PaymentLine fi_line = null;
	private Mhrmpaymentlist[] salary = null;
	private Mhrmpayment hrm_payment_ID = null;
	Timestamp dateFrom = null;
	int C_BPartner_ID = 0;
	int C_Payment_ID = 0;
	BigDecimal hrm_result = new BigDecimal(0);

	@Override
	protected void prepare() {
		
		payment = new X_C_Payment(getCtx(), getRecord_ID(), null);

	}

	
	@Override
	protected String doIt() throws Exception {
		
		C_Payment_ID = payment.getC_Payment_ID();		
		hrm_payment_ID = Mhrmpayment.get(getCtx(), payment.gethrm_payment_ID());
		if (hrm_payment_ID == null || hrm_payment_ID.get_ID() == 0)
			throw new AdempiereException (" Null value in field hrm_payment_id ");		
		dateFrom = hrm_payment_ID.getDateFrom();
		salary = Mhrmpaymentlist.getCount(dateFrom);	
		//int count = Mhrmpayment.getSalarySumCount(dateFrom);
		for (int i=0; i < salary.length; i++){		
			C_BPartner_ID = salary[i].getC_BPartner_ID();
			
			if (payment.getFI_TypeOfTax().getFI_TypeOfTax_ID() == 1000036
					|| payment.getFI_TypeOfTax().getFI_TypeOfTax_ID() == 1000037){         // COTCH
				hrm_result = Mhrmpayment.getSalarySum_COTCH(C_BPartner_ID, dateFrom);
			}else if (payment.getFI_TypeOfTax().getFI_TypeOfTax_ID() == 1000040
						|| payment.getFI_TypeOfTax().getFI_TypeOfTax_ID() == 1000041){   // OPV
				hrm_result = Mhrmpayment.getSalarySum_OPV(C_BPartner_ID, dateFrom);
			}
			
			if (hrm_result != new BigDecimal(0)){
			fi_line = MFI_C_PaymentLine.getSelect(C_BPartner_ID, C_Payment_ID);
				if (fi_line == null || fi_line.get_ID() == 0)
					fi_line = new MFI_C_PaymentLine(getCtx(), 0, null);
				fi_line.setAD_Org_ID(Env.getAD_Org_ID(getCtx()));
				fi_line.setC_Payment_ID(C_Payment_ID);
				fi_line.setC_BPartner_ID(C_BPartner_ID);
				fi_line.setAmount(hrm_result);
				fi_line.saveEx();
			}
		}
		
	return Msg.translate(Env.getCtx(), "Success");
	
	}
}
